TOOLCHAIN ?= arm-linux-gnueabi-
CC = $(TOOLCHAIN)gcc
AS = $(TOOLCHAIN)as
OBJCOPY = $(TOOLCHAIN)objcopy

CFLAGS := -march=armv4t -mthumb -Wall -Werror -Os -MMD -ffreestanding \
	-fno-common	-fomit-frame-pointer -nostdlib -fno-builtin-printf \
	-fno-asynchronous-unwind-tables -fPIE -fno-builtin -fno-exceptions \
	-Wl,--no-dynamic-linker,--build-id=none,-T,romhax.ld
CXXFLAGS := $(CFLAGS) -std=gnu++14
CFLAGS += -std=gnu11

# shameless copypasta from https://stackoverflow.com/a/2908351/375416
C_FILES := $(wildcard *.c)
S_FILES := $(wildcard *.S)
OBJ_FILES := $(addprefix obj/,$(notdir $(C_FILES:.c=.o)))
OBJ_FILES += $(addprefix obj/,$(notdir $(S_FILES:.S=.o)))
-include $(OBJFILES:.o=.d)

all: cbfs.bin

obj/%.o: %.c
	$(CC) $(CFLAGS) -c -o $@ $<

obj/%.o: %.S
	$(AS) -c -o $@ $<

%.bin: %.elf
	$(OBJCOPY) -O binary $< $@

cbfs.elf: obj/cbfs.o obj/common.o obj/vsprintf.o obj/idiv.o obj/idivmod.o obj/thumb_case.o
	$(CC) $(CFLAGS) -o $@ $^

clean:
	rm -f $(OBJ_FILES)
	rm -f cbfs.bin cbfs.elf
